package code.lucamarrocco.struts2.rest.sample;

import java.util.HashSet;
import java.util.Set;
import java.util.WeakHashMap;

public class UnitOfWork {
	private static ThreadLocal current = new ThreadLocal();

	private static WeakHashMap<Long, UnitOfWork> unitOfWorks = new WeakHashMap<Long, UnitOfWork>();

	public static UnitOfWork NewUnitOfWork() {
		UnitOfWork newUnitOfWork = new UnitOfWork();
		newUnitOfWork.id = newId++;
		setUnitOfWork(newUnitOfWork);
		return newUnitOfWork;
	}

	public static void setUnitOfWork(UnitOfWork unitOfWork) {
		unitOfWorks.put(unitOfWork.getId(), unitOfWork);
		current.set(unitOfWork);
	}

	public static UnitOfWork UnitOfWork() {
		UnitOfWork unitOfWork = (UnitOfWork) current.get();
		if (unitOfWork == null) unitOfWork = NewUnitOfWork();
		return unitOfWork;
	}

	public static UnitOfWork UnitOfWork(String id) {
		if (unitOfWorks.containsKey(id)) return unitOfWorks.get(id);
		return NewUnitOfWork();
	}

	private Long id = 0l;

	private static Long newId = 0l;

	private Set<Object> newObjects = new HashSet<Object>();

	private Set<Object> deletedObjects = new HashSet<Object>();

	private Set<Object> dirtyObjects = new HashSet<Object>();

	public void commit(UnitOfWork unitOfWork) {
		insertNew();
		updateDirty();
		deleteRemoved();
	}

	private void deleteRemoved() {

	}

	public Set<Object> getDeletedObjects() {
		return deletedObjects;
	}

	public Set<Object> getDirtyObjects() {
		return dirtyObjects;
	}

	public Long getId() {
		return id;
	}

	public Set<Object> getNewObjects() {
		return newObjects;
	}

	private void insertNew() {

	}

	public void registerClean(Object object) {}

	public void registerDeleted(Object object) {
		deletedObjects.add(object);
	}

	public void registerDirty(Object object) {
		dirtyObjects.add(object);
	}

	public void registerNew(Object object) {
		newObjects.add(object);
	}

	public void rollback() {

	}

	private void updateDirty() {

	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		return stringBuilder.toString().replaceAll(", $", "");
	}
}